package org.road0329.dlt698.axdr;

import org.road0329.dlt698.ReverseByteArrayInputStream;
import org.road0329.dlt698.ReverseByteArrayOutputStream;
import org.road0329.dlt698.asn1.axdr.AxdrOptional;
import org.road0329.dlt698.asn1.axdr.AxdrType;

import java.io.IOException;
import java.nio.Buffer;
import java.nio.ByteBuffer;


public class Security_Response extends AxdrType {
    private ByteBuffer dataCode = null;
    private SubChoiceAppUnit appUnit = null;
    private AxdrOptional<SubChoiceDataValid> dataValid = new AxdrOptional<SubChoiceDataValid>(new SubChoiceDataValid(), false);

    public Security_Response() {
    }

    public void set_dataCode(ByteBuffer dataCode) {
        this.dataCode = dataCode;
    }

    public void set_all(SubChoiceAppUnit appUnit, SubChoiceDataValid dataValid) {
        this.appUnit = appUnit;
        this.dataValid.setValue(dataValid);
    }

    public int decode(ReverseByteArrayInputStream input) throws Exception {
        int codeLength = 0;
        this.appUnit = new SubChoiceAppUnit();
        codeLength += this.appUnit.decode(input);
        this.dataValid = new AxdrOptional(new SubChoiceDataValid(), false);
        codeLength += this.dataValid.decode(input);
        return codeLength;
    }

    public int encode(ReverseByteArrayOutputStream output) throws Exception {
        int codeLength;
        if (this.dataCode != null) {
            codeLength = this.dataCode.capacity();
            for (int i = this.dataCode.capacity() - 1; i >= 0; i--) {
                output.write(this.dataCode.get(i));
            }
        } else {
            if (this.appUnit != null && this.dataValid != null) {
                codeLength = 0;
                codeLength += this.dataValid.encode(output);
                codeLength += this.appUnit.encode(output);
            } else {
                throw new Exception("dataValid or appUnit is null");
            }
        }
        return codeLength;
    }

    public void encodeAndSave(int encodingSizeGuess) throws Exception {
        ReverseByteArrayOutputStream revOStream = new ReverseByteArrayOutputStream();
        revOStream.setBufSize(encodingSizeGuess);
        encode(revOStream);
        this.dataCode = ByteBuffer.wrap(revOStream.getArray());
    }

    public String toString() {
        if (this.appUnit != null && this.dataValid != null) {
            return "sequence: {" + "appUnit: " + this.appUnit + ", dataValid: " + this.dataValid + "}";
        } else {
            return "appUnit or dataValid is null";
        }
    }
}



